package com.coffee.mybatis;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusPropertiesCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.DynamicTableNameInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.support.JdbcTransactionManager;

import javax.sql.DataSource;
import java.util.Objects;

@Configuration
public class MybatisConfiguration {

    @Bean
    @ConditionalOnMissingBean(name = "auditMetaObjectHandler")
    public AuditMetaObjectHandler auditMetaObjectHandler() {
        return new AuditMetaObjectHandler();
    }

    @Bean
    @ConditionalOnMissingBean(name = "identifierGenerator")
    public MochaIdentifierGenerator identifierGenerator() {
        return new MochaIdentifierGenerator();
    }

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        return new MybatisPlusInterceptor();
    }

    @Bean
    public DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor(DynamicTableNameConfigProperties dynamicTableNameConfigProperties, MybatisPlusInterceptor interceptor) {
        DynamicTableNameInnerInterceptor inner = new DynamicTableNameInnerInterceptor();
        inner.setTableNameHandler(new CoffeeDynamicTableNameHandler(dynamicTableNameConfigProperties));
        CoffeeMybatisInterceptor.addInterceptor(interceptor, inner);
        return inner;
    }

    @Bean
    public PaginationInnerInterceptor paginationInterceptor(MybatisPlusInterceptor interceptor) {
        PaginationInnerInterceptor inner = new PaginationInnerInterceptor(DbType.MYSQL);
        CoffeeMybatisInterceptor.addInterceptor(interceptor, inner);
        return inner;
    }

    @Bean(name = "jdbcTransactionManager")
    @Primary
    public JdbcTransactionManager coffeeTransactionManager(DataSource dataSource){
        return new JdbcTransactionManager(dataSource);
    }


    @Bean
    public MybatisPlusPropertiesCustomizer propertiesCustomizer(){
        return properties -> {
            MybatisPlusProperties.CoreConfiguration configuration = properties.getConfiguration();
            if (Objects.isNull(configuration)) configuration = new MybatisPlusProperties.CoreConfiguration();
            configuration.setDefaultEnumTypeHandler(CoffeeEnumTypeHandler.class);
            properties.setConfiguration(configuration);
        };
    }


}
